//
//  AppDelegate.m
//  planning
//
//  Created by mac on 2019/7/22.
//  Copyright © 2019 mac. All rights reserved.
//

#import "AppDelegate.h"
#import <AVFoundation/AVFoundation.h>
#import "MyHttpServer.h"
#import "AppContext.h"
#import "WxMgr.h"
#import "AppConfig.h"
#import "HCKeepBGRunManager.h"
#import "LoginController.h"
#import <WindSDK/WindSDK.h>

@interface AppDelegate () <BUSplashAdDelegate>

@property (nonatomic, assign) CFTimeInterval startTime;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    [self beginReceiving:application];
    
    //当HUD显示的时候，不允许用户交互，且显示黑色背景图层
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    //修改显示时间
    [SVProgressHUD setMinimumDismissTimeInterval:2.0];
    
    //初始化微信相关信息
    [WxMgr sharedWxMgr];
    
    //服务器版本号
    [[AppContext sharedContext] setVersionCode:kVer];
    
    //用户渠道
    [[AppContext sharedContext] setCurChannel:kCHANNEL];
    
    if ([AppContext sharedContext].isVip!=0) {
        if ([AppContext sharedContext].isVip==1) {
            [self skip];
        }else if ([AppContext sharedContext].isVip==-1 || [AppContext sharedContext].isVip==-2) {
            UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
            UIViewController *vc = [storyboard instantiateInitialViewController];
            self.window.rootViewController = vc;
        }
    }else {
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        NSString *text=pasteboard.string;
        if ([text hasPrefix:LOAD_TAG]) {
            //判断剪切板的这个字符串来判断是否条转到哪个页面
            [self skip];
            [AppContext sharedContext].loadtag=text;
            [AppContext sharedContext].isVip = 1;
            NSString *past = [text componentsSeparatedByString:LOAD_TAG].lastObject;
            if (![past isEqual:@""]) {
               [[AppContext sharedContext] setCurChannel:past];
            }
        }else {
            LoginController *loginVc = [[LoginController alloc] init];
            self.window.rootViewController = loginVc;
            loginVc.block = ^(NSInteger index) {
                if (index==1) {
                    [self skip];
                }else {
                    UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
                    UIViewController *vc = [storyboard instantiateInitialViewController];
                    self.window.rootViewController = vc;
                }
            };
        }
    }
    
    //网盟
    [BUAdSDKManager setAppID:kUnionADID];
    [BUAdSDKManager setIsPaidApp:NO];
    [BUAdSDKManager setLoglevel:BUAdSDKLogLevelDebug];
    
    CGRect frame = [UIScreen mainScreen].bounds;
    BUSplashAdView *splashView = [[BUSplashAdView alloc] initWithSlotID:kBUSplashAdID frame:frame];
    // tolerateTimeout = CGFLOAT_MAX , The conversion time to milliseconds will be equal to 0
    splashView.tolerateTimeout = 3;
    splashView.delegate = self;
    
    UIWindow *keyWindow = self.window;
    self.startTime = CACurrentMediaTime();
    [splashView loadAdData];
    [keyWindow.rootViewController.view addSubview:splashView];
    splashView.rootViewController = keyWindow.rootViewController;
    
    [self.window makeKeyAndVisible];
    
    return YES;
}

- (void)skip {
    
    //开启httpsServer服务
    [[MyHttpServer shared] startServer];
    
    UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
    UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"main"];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    self.window.rootViewController = nav;
    
    // 通过个推平台分配的appId、 appKey 、appSecret 启动SDK，注：该方法需要在主线程中调用
    dispatch_async(dispatch_get_main_queue(), ^{
        [GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self];
    });
    
    // 注册 APNs
    [self registerRemoteNotification];
    
    //初始化SDK
    WindAdOptions *options = [WindAdOptions options];
    options.appId = kSigmobAPPID;
    options.apiKey = kSigmobAPPKey;
    [WindAds startWithOptions:options];
    
}


// 注册 APNs
- (void)registerRemoteNotification {
    /*
     警告：Xcode8 需要手动开启"TARGETS -> Capabilities -> Push Notifications"
     */
    
    /*
     警告：该方法需要开发者自定义，以下代码根据 APP 支持的 iOS 系统不同，代码可以对应修改。
     以下为演示代码，注意根据实际需要修改，注意测试支持的 iOS 系统都能获取到 DeviceToken
     */
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 // Xcode 8编译会调用
        if (@available(iOS 10.0, *)) {
            UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
            center.delegate = self;
            [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
                if (!error) {
                    NSLog(@"request authorization succeeded!");
                }
            }];
        } else {
            // Fallback on earlier versions
        }
        
        [[UIApplication sharedApplication] registerForRemoteNotifications];
#else // Xcode 7编译会调用
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
#endif
    } else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    } else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
        //写在这个中间的代码,都不会被编译器提示-Wdeprecated-declarations类型的警告
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |UIRemoteNotificationTypeSound |UIRemoteNotificationTypeBadge);
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
#pragma clang diagnostic pop
        
    }
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [[WxMgr sharedWxMgr] handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
    return [[WxMgr sharedWxMgr] handleOpenURL:url];
}

/** 远程通知注册成功委托 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // [3]:向个推服务器注册deviceToken 为了方便开发者，建议使用新方法
    //25ada7e283c536d9eaef501e86e2ac736bd6eb0edfe0b53fe077c94bd05b95d4
    NSLog(@"deviceToken===%@",deviceToken);
    [GeTuiSdk registerDeviceTokenData:deviceToken];
}

/** APP已经接收到“远程”通知(推送) - 透传推送消息 {app 在后台没杀死或者杀死 点击通知 首先进入的方法} */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    self.isLaunchedByNotification = YES;
    // 将收到的APNs信息传给个推统计
    [GeTuiSdk handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
//  iOS 10: App在前台获取到通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler  API_AVAILABLE(ios(10.0)){
    
    NSLog(@"willPresentNotification：%@", notification.request.content.userInfo);
    
    // 根据APP需要，判断是否要提示用户Badge、Sound、Alert
    completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}

//  iOS 10: 点击通知进入App时触发，在该方法内统计有效用户点击数
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler  API_AVAILABLE(ios(10.0)){
    
    NSLog(@"didReceiveNotification：%@", response.notification.request.content.userInfo);
    
    self.isLaunchedByNotification = YES;
    // [ GTSdk ]：将收到的APNs信息传给个推统计
    [GeTuiSdk handleRemoteNotification:response.notification.request.content.userInfo];
    
    completionHandler();
}
#endif

/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    //个推SDK已注册，返回clientId
    NSLog(@"\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"uid"] = [AppContext sharedContext].curUid;
    dict[@"cid"] = clientId;
    [[AppContext sharedContext] setClientId:clientId];
    [[ApiClient sharedApi] getui_cid:dict cd:^(NSDictionary *data, NSError *connectionError) {
        NSLog(@"data1:%@",data);
    }];
}

/** SDK收到透传消息回调 {app在前台 只走这一个方法}{app在后台，进来前台第二个走的方法}*/
- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    //收到个推消息
    NSString *payloadMsg = nil;
    if (payloadData) {
        payloadMsg = [[NSString alloc] initWithBytes:payloadData.bytes length:payloadData.length encoding:NSUTF8StringEncoding];
    }
    
    NSDictionary *payLoadMegDic = [NSJSONSerialization JSONObjectWithData:payloadData options:NSJSONReadingMutableLeaves error:nil];
    NSLog(@"%@",payLoadMegDic);
    if (offLine) {
        if (payLoadMegDic) {
            if (self.isLaunchedByNotification) { // app是通过点击通知栏进入前台
                //                UITabBarController *_tab = (UITabBarController *)(self.window.rootViewController);
                //                UINavigationController *nva = (UINavigationController *)_tab.viewControllers[_tab.selectedIndex];
                // 根据payLoadMegDic判断跳转类型
                self.isLaunchedByNotification = NO;
            }else{
                // app是通过点击icon进入前台，在这里不做操作
            }
        }
        
        NSString *msg = [NSString stringWithFormat:@"taskId=%@,messageId:%@,payloadMsg:%@%@",taskId,msgId, payloadMsg,offLine ? @"<离线消息>" : @""];
        NSLog(@"\n>>>[GexinSdk ReceivePayload]:%@\n\n", msg);
        
    }else if(!self.isLaunchedByNotification){
        // app已经处于前台，提示框提示
        // 在这里拿不到apns 里的title body! 如果想要处理的话可以让服务端把aps 的内容传到transmissionContent 透传内容里 ，应用在线的时候可以拿到这个透传
        self.isLaunchedByNotification = NO;
        // 转换成一个本地通知，显示到通知栏，你也可以直接显示出一个alertView，只是那样稍显aggressive
        
        NSString *title=[NSString stringWithFormat:@"%@",payLoadMegDic[@"title"]];
        
        NSString *detail=[NSString stringWithFormat:@"%@",payLoadMegDic[@"text"]];
        
        NSLog(@"title===%@  detail===%@",title,detail);
        
        if (@available(iOS 10.0, *)) {
//            [self registerNotification:1 andTitle:title andMess:detail];
        } else {
//            [self registerLocalNotificationInOldWay:1 andTitle:title andMess:detail];
        }
    }
}

- (void)beginReceiving:(UIApplication *)application {
    
    // 设置音频会话类型
    AVAudioSession *session = [AVAudioSession  sharedInstance];
    
    [session setCategory:AVAudioSessionCategoryPlayback  error:nil];
    
    [session setActive:YES error:nil];
    
    // 接收远程事件
    [application beginReceivingRemoteControlEvents];
}

/**
 *  锁屏按钮的远程通知
 */
- (void)remoteControlReceivedWithEvent:(UIEvent *)event
{
    if (event.type == UIEventTypeRemoteControl) {
        
        if (self.removteBlock) {
            self.removteBlock(event);
        }
    }
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // app启动或者app从后台进入前台都会调用这个方法
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
    // app从后台进入前台都会调用这个方法
    [[HCKeepBGRunManager shareManager] stopBGRun];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
//     NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
//     NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];
//
//    NSLog(@"current1=%@",timeSp);
    // 开启后台任务
    [application beginBackgroundTaskWithExpirationHandler:nil];
    [[HCKeepBGRunManager shareManager] startBGRun];
    
}

- (void)splashAdDidClose:(BUSplashAdView *)splashAd {
    [splashAd removeFromSuperview];
    CFTimeInterval endTime = CACurrentMediaTime();
    NSLog(@"Total Runtime: %g s", endTime - self.startTime);
}

- (void)splashAd:(BUSplashAdView *)splashAd didFailWithError:(NSError *)error {
    [splashAd removeFromSuperview];
    CFTimeInterval endTime = CACurrentMediaTime();
    NSLog(@"Total Runtime: %g s error=%@", endTime - self.startTime, error);
}

@end
